<template>
	<div>
		<jk-dialog
			v-model="showDialog"
			title="创建-工艺单"
			width="1100px"
			:show-content-loading="showLoading"
			:confirm-btn-loading="confirmBtnLoading"
			append-to-body
			@on-cancel="onVisibleChange(false)"
			@on-visible-change="onVisibleChange"
			@on-confirm="onConfirmBtn"
		>
			<el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="120px" :show-message="false">
				<div ref="box1">
					<div class="flex-between-center margin-bottom-10">
						<el-tag type="primary" effect="plain">
							<span class="el-icon-tickets item-gap"></span>
							<span>基本信息</span>
						</el-tag>
						<jk-button type="primary" icon="el-icon-document-copy" size="mini" @click="selectDialogState = true">从已有单据复制</jk-button>
					</div>
					<el-row>
						<el-col :xl="8" :lg="8" :md="12" :sm="12" :xs="24">
							<el-form-item class="margin-bottom-10" label="用户工艺编号">
								<el-input v-model.trim="ruleForm.code" clearable style="width: 100%;" placeholder="用户工艺编号" />
							</el-form-item>
						</el-col>
						<el-col :xl="8" :lg="8" :md="12" :sm="12" :xs="24">
							<el-form-item class="margin-bottom-10" label="单据日期" prop="specDate">
								<el-date-picker v-model="ruleForm.specDate" clearable type="date" style="width: 100%;" value-format="yyyy-MM-dd" placeholder="单据日期" />
							</el-form-item>
						</el-col>
						<el-col :xl="8" :lg="8" :md="12" :sm="12" :xs="24">
							<el-form-item class="margin-bottom-10" label="品种名称" prop="productId">
								<remote-search-product-input
									placeholder="品种名称"
									only-key="productId"
									query-name="productName"
									:form-data="ruleForm"
									@on-select="onSelectProductChange"
								></remote-search-product-input>
							</el-form-item>
						</el-col>
						<el-col :xl="8" :lg="8" :md="12" :sm="12" :xs="24">
							<el-form-item class="margin-bottom-10" label="批号" prop="batchCode">
								<remote-search-batch-code-input
									:disabled="!ruleForm.productId"
									placeholder="批号"
									only-key="batchCodeId"
									query-name="batchCode"
									:form-data="ruleForm"
									@on-select="onSelectBatchCodeChange"
								></remote-search-batch-code-input>
							</el-form-item>
						</el-col>
						<el-col :xl="8" :lg="8" :md="12" :sm="12" :xs="24">
							<el-form-item class="margin-bottom-10" label="纺纱方式" prop="spinTypeId">
								<jk-select v-model="ruleForm.spinTypeId" :option-list="spinTypeList" size="medium" placeholder="纺纱方式" clearable class="width-100-percent" @change="onSpinTypeChange"></jk-select>
							</el-form-item>
						</el-col>
						<el-col :xl="8" :lg="8" :md="12" :sm="12" :xs="24">
							<el-form-item class="margin-bottom-10" label="工序" prop="processId">
								<el-select v-model="ruleForm.processId" placeholder="工序" clearable class="width-100-percent" @change="onProcessChange">
									<el-option v-for="item in processList" :key="item.id" :label="item.name" :value="item.id" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xl="8" :lg="8" :md="12" :sm="12" :xs="24">
							<el-form-item class="margin-bottom-10" label="设备机型" prop="machineModelId">
								<el-select v-model="ruleForm.machineModelId" placeholder="设备机型" clearable class="width-100-percent" @change="onProcessChange">
									<el-option v-for="item in machineModelList" :key="item.id" :label="item.name" :value="item.id" />
								</el-select>
							</el-form-item>
						</el-col>
						<!--<el-col :xl="8" :lg="8" :md="12" :sm="12" :xs="24">
                            <el-form-item class="margin-bottom-10" label="台日单产" prop="dailyYield1">
                                <jk-number-input v-model="ruleForm.dailyYield" placeholder="台日单产" />
                            </el-form-item>
                        </el-col>-->
						<el-col :xl="8" :lg="8" :md="12" :sm="12" :xs="24">
							<el-form-item class="margin-bottom-10" label="定量(g/m)">
								<div class="flex-start">
									<jk-number-input v-model="ruleForm.gramWeight" :disabled="!!ruleForm.specSheetId" style="width: 100%;" placeholder="克重" />
									<span>~</span>
									<jk-number-input v-model="ruleForm.meters" :disabled="!!ruleForm.specSheetId" style="width: 100%;" placeholder="米长" />
								</div>
							</el-form-item>
						</el-col>
						<el-col :xl="8" :lg="8" :md="12" :sm="12" :xs="24">
							<el-form-item class="margin-bottom-10" label="工艺员" prop="specEmpId">
								<remote-search-emp-input
									placeholder="工艺员"
									only-key="specEmpId"
									query-name="specEmpName"
									:form-data="ruleForm"
									@on-select="onSelectEmpChange"
								></remote-search-emp-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>
				<el-tag ref="box3" type="primary" effect="plain" class="margin-bottom-4">
					<span class="el-icon-notebook-2 item-gap"></span>
					<span>工艺项目</span>
				</el-tag>
				<el-row>
					<el-col :span="24">
						<jk-table ref="jkTable" v-loading="tableLoading" :data="ruleForm.specSheetParamList" border :height="dialogTableHeight - 10" style="width: 100%">
							<vxe-table-column type="seq" title="序号" width="60" align="center" />
							<vxe-table-column field="specParamName" title="工艺项目" :min-width="140"></vxe-table-column>
							<vxe-table-column field="val" title="标准值" align="right" :min-width="120">
								<template slot-scope="scope">
									<div>
										<jk-number-input v-if="scope.row.dataType === 1" v-model="scope.row.val" size="mini" @keydown.enter.native="handleKeyDown" @change="onErrPerChange($event, scope)"></jk-number-input>
										<jk-input v-else v-model="scope.row.val" size="mini" placeholder="" @keydown.enter.native="handleKeyDown"></jk-input>
									</div>
								</template>
							</vxe-table-column>
							<vxe-table-column field="valMin" title="误差(%)" align="right" :width="120">
								<template slot-scope="scope">
									<span v-if="!scope.row.val">{{ scope.row.plusOrMinus }}</span>
									<jk-number-input v-else v-model="scope.row.plusOrMinus" size="mini" @keydown.enter.native="handleKeyDown" @change="onErrPerChange($event, scope)"></jk-number-input>
								</template>
							</vxe-table-column>
							<vxe-table-column field="valMin" title="下限值" align="right" :min-width="120">
								<template slot-scope="scope">
									<div>
										<jk-number-input v-if="scope.row.dataType === 1" v-model="scope.row.valMin" size="mini" @keydown.enter.native="handleKeyDown"></jk-number-input>
										<jk-input v-else v-model="scope.row.valMin" size="mini" placeholder="" @keydown.enter.native="handleKeyDown"></jk-input>
									</div>
								</template>
							</vxe-table-column>
							<vxe-table-column field="valMax" title="上限值" align="right" :min-width="120">
								<template slot-scope="scope">
									<div>
										<jk-number-input v-if="scope.row.dataType === 1" v-model="scope.row.valMax" size="mini" @keydown.enter.native="handleKeyDown"></jk-number-input>
										<jk-input v-else v-model="scope.row.valMax" size="mini" placeholder="" @keydown.enter.native="handleKeyDown"></jk-input>
									</div>
								</template>
							</vxe-table-column>
							<vxe-table-column field="dataType" title="数据类型" :width="100" align="center">
								<template slot-scope="scope">
									{{ scope.row.dataType === 1 ? '数字' : '字符' }}
								</template>
							</vxe-table-column>
						</jk-table>
					</el-col>
				</el-row>
			</el-form>
		</jk-dialog>
		<select-dialog
			:dialog-state="selectDialogState"
			:form-data="{
				processId: ruleForm.processId,
				productName: ruleForm.productName,
				batchCode: ruleForm.batchCode,
				machineModelName: ruleForm.machineModelName,
				spinTypeId: ruleForm.spinTypeId,
			}"
			@on-visible-change="onVisibleChangeOfSelectDialog"
			@on-confirm="onConfirmBtnOfSelectDialog"
		></select-dialog>
	</div>
</template>
<script>
    import formBox from '../order/components/form-box';
    import {
        spinSpecSheetCreate, spinSpecSheetGet
    } from '../../../api/technology/order';
    import jkSaveButton from '../../jk-components/jk-save-button';
    import jkUpdateButton from '../../jk-components/jk-update-button';
    import remoteSearchProductInput from '../order/components/remote-search-product-input';
    import remoteSearchEmpInput from '../order/components/remote-search-emp-input';
    import remoteSearchBatchCodeInput from '../../production/qhPrd/productConfigCotton/components/remote-search-batch-code-input';
    import { formatDate } from '../../../utils/jk/jk-tool';
    import { spinMachineModelPage } from '../../../api/basicData/machineModel';
    import calDialogHeight from '../../../mixins/cal-dialog-height';
    import { spinSpecSheetTaskGet } from '../../../api/production/xsNotice';
    import { systemBusinessDictPage } from '../../../api/basicData/businessDict';
    import { mathJsAdd, mathJsMul, mathJsSub } from '../../../utils/jk/jk-cals';
    import { spinTechnologyModelPage } from '../../../api/technology/item';
    import selectDialog
        from '../../production/order/components/remote-search-technology-order-input/radio-select-dialog';
    export default {
        mixins: [calDialogHeight],
        props: {
            taskId: {
                type: [String, Number],
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            codeList: {
                type: Array,
                default() {
                    return [];
                }
            },
            defaultData: {
                type: Object,
                default() {
                    return {};
                }
            }
        },
        components: { selectDialog, formBox, jkSaveButton, jkUpdateButton, remoteSearchProductInput, remoteSearchEmpInput, remoteSearchBatchCodeInput },
        data() {
            return {
                prefix: 'spin:specSheet',
                apiItem: {
                    'save': spinSpecSheetCreate
                },
                selectDialogState: false,
                spinTypeList: [],
                tableLoading: false,
                processList: [],
                updateAuditLoading: false,
                auditStateLoading: false,
                confirmBtnLoading: false,
                workshopList: [],
                saveDialogState: false,
                machineModelList: [],
                ruleForm: {
                    'code': '',
                    'batchCode': '',
                    'dailyYield': null,
                    'efficiencyPercent': null,
                    'fixedLength': null,
                    'gramWeight': null,
                    'machineModelCode': '',
                    'machineModelId': null,
                    'machineModelName': '',
                    'meters': null,
                    'moistureRegain': null,
                    'numbers': null,
                    'processCode': '',
                    'processId': null,
                    'processName': '',
                    'productCode': '',
                    'productId': null,
                    'productModels': '',
                    'productName': '',
                    'specDate': '',
                    'specEmpId': null,
                    'specEmpName': ''
                },
                rules: {
                    gramWeight: [{ required: true, trigger: 'change' }],
                    meters: [{ required: true, trigger: 'change' }],
                    spinTypeId: [{ required: true, trigger: 'change' }],
                    fixedLength: [{ required: true, trigger: 'change' }],
                    efficiencyPercent: [{ required: true, trigger: 'change' }],
                    dailyYield: [{ required: true, trigger: 'change' }],
                    specEmpId: [{ required: true, trigger: 'change' }],
                    productId: [{ required: true, trigger: 'change' }],
                    machineModelId: [{ required: true, trigger: 'change' }],
                    batchCode: [{ required: true, trigger: 'change' }],
                    processId: [{ required: true, trigger: 'change' }],
                    code: [{ required: true, trigger: 'change' }],
                    name: [{ required: true, trigger: 'change' }]
                },
                showDialog: false,
                showLoading: false
            };
        },
        methods: {
            handleKeyDown(event) {
                if (event.key === 'Enter') {
                    event.preventDefault(); // 阻止默认行为

                    // 获取当前聚焦的元素
                    const currentElement = document.activeElement;

                    // 获取所有可聚焦的元素
                    const focusableElements = document.querySelectorAll('input');
                    const currentIndex = Array.from(focusableElements).indexOf(currentElement);

                    // 计算下一个应该聚焦的元素
                    const nextIndex = (currentIndex + 1) % focusableElements.length;
                    const nextElement = focusableElements[nextIndex];

                    // 将焦点转移到下一个元素
                    nextElement.focus();
                }
            },
            onConfirmBtnOfSelectDialog(e) {
                if (!e) return;
                spinSpecSheetGet({
                    id: e.id
                }).then(res => {
                    if (res.data.status === 200) {
                        this.selectDialogState = false;
                        const resData = res.data.res || {};
                        resData.specSheetParamList = resData.specSheetParamList || [];
                        delete resData.id;
                        resData.specSheetParamList.forEach(x => {
                            delete x.id;
                        });
                        resData.belongDate = formatDate(Date.now());
                        resData.code = '';
                        resData.specEmpId = this.$store.state.user.empInfo.id;
                        resData.specEmpName = this.$store.state.user.empInfo.name;
                        this.ruleForm = resData;
                    }
                });
            },
            onVisibleChangeOfSelectDialog(e) {
                this.selectDialogState = e;
            },
            onErrPerChange(e, scope) {
                if (e && this.ruleForm.specSheetParamList[scope.rowIndex].dataType === 1 && this.ruleForm.specSheetParamList[scope.rowIndex].plusOrMinus) {
                    let val = mathJsMul(this.ruleForm.specSheetParamList[scope.rowIndex].val, (this.ruleForm.specSheetParamList[scope.rowIndex].plusOrMinus / 100));
                    val = Number(val.toFixed(2));
                    this.$set(this.ruleForm.specSheetParamList[scope.rowIndex], 'valMin', mathJsSub(this.ruleForm.specSheetParamList[scope.rowIndex].val, val));
                    this.$set(this.ruleForm.specSheetParamList[scope.rowIndex], 'valMax', mathJsAdd(this.ruleForm.specSheetParamList[scope.rowIndex].val, val));
                } else {
                    if (this.ruleForm.specSheetParamList[scope.rowIndex].dataType === 1) {
                        this.$set(this.ruleForm.specSheetParamList[scope.rowIndex], 'valMin', this.ruleForm.specSheetParamList[scope.rowIndex].val);
                        this.$set(this.ruleForm.specSheetParamList[scope.rowIndex], 'valMax', this.ruleForm.specSheetParamList[scope.rowIndex].val);
                    }
                }
            },
            onSpinTypeChange() {
                this.$set(this.ruleForm, 'specSheetParamList', []);
                this.getTechnologyItemListRequest();
            },
            onEditBtn() {
                this.$toOtherRouter({
                    name: 'editTechnology',
                    query: {
                        id: this.$route.query.id ? Number(this.$route.query.id) : null
                    }
                });
            },
            // 获取工艺任务的详情
            getTechnologyTaskDetailRequest(id) {
                return spinSpecSheetTaskGet({ id }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || {};
                        this.$set(this.ruleForm, 'productId', resData.productId);
                        this.$set(this.ruleForm, 'productCode', resData.productCode);
                        this.$set(this.ruleForm, 'productName', resData.productName);
                        this.$set(this.ruleForm, 'productModels', resData.productModels);

                        this.$set(this.ruleForm, 'spinTypeId', resData.spinTypeId);
                        this.$set(this.ruleForm, 'spinTypeCode', resData.spinTypeCode);
                        this.$set(this.ruleForm, 'spinTypeName', resData.spinTypeName);

                        this.$set(this.ruleForm, 'machineModelId', resData.machineModelId);
                        this.$set(this.ruleForm, 'machineModelCode', resData.machineModelCode);
                        this.$set(this.ruleForm, 'machineModelName', resData.machineModelName);

                        this.$set(this.ruleForm, 'batchId', resData.batchId);
                        this.$set(this.ruleForm, 'batchCode', resData.batchCode);
                        const processItem = resData.prdNotice ? this.processList.find(x => x.code.toUpperCase() === (resData.prdNotice.processCode ? resData.prdNotice.processCode : 'XS').toUpperCase()) : {};
                        this.$set(this.ruleForm, 'processId', processItem.id);
                        this.$set(this.ruleForm, 'processCode', processItem.code);
                        this.$set(this.ruleForm, 'processName', processItem.name);
                    }
                });
            },
            getSpinTypeListRequest() {
                return systemBusinessDictPage({ categoryCode: 'SPIN_TYPE' }).then(res => {
                    if (res.data.status === 200) {
                        this.spinTypeList = res.data.res || [];
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                this.$nextTick(() => {
                    this.$refs.ruleForm.clearValidate();
                });
                if (this.codeList && this.codeList.length) {
                    this.$set(this.ruleForm, 'code', this.codeList[0]);
                }
                this.processList = this.$store.state.user.userProcess.processList;
                if (!this.ruleForm.processId) this.$set(this.ruleForm, 'processId', this.$store.state.user.userProcess.defaultProcessId || null);
                if (this.defaultData) {
                    this.$set(this.ruleForm, 'productId', this.defaultData.productId);
                    this.$set(this.ruleForm, 'productCode', this.defaultData.productCode);
                    this.$set(this.ruleForm, 'productName', this.defaultData.productName);
                    this.$set(this.ruleForm, 'productModels', this.defaultData.productModels);
                    this.$set(this.ruleForm, 'spinTypeId', this.defaultData.spinTypeId);
                    this.$set(this.ruleForm, 'spinTypeCode', this.defaultData.spinTypeCode);
                    this.$set(this.ruleForm, 'spinTypeName', this.defaultData.spinTypeName);
                    this.$set(this.ruleForm, 'batchId', this.defaultData.batchId);
                    this.$set(this.ruleForm, 'batchCode', this.defaultData.batchCode);

                    this.$set(this.ruleForm, 'machineModelId', this.defaultData.machineModelId);
                    this.$set(this.ruleForm, 'machineModelCode', this.defaultData.machineModelCode);
                    this.$set(this.ruleForm, 'machineModelName', this.defaultData.machineModelName);
                }

                this.$set(this.ruleForm, 'specDate', formatDate(Date.now()));
                this.$set(this.ruleForm, 'specEmpId', this.$store.state.user.empInfo.id);
                this.$set(this.ruleForm, 'specEmpName', this.$store.state.user.empInfo.name);
                await this.getSpinTypeListRequest();
                await this.getMachineModelListRequest();
                // 来源工艺任务时
                if (this.taskId) await this.getTechnologyTaskDetailRequest(this.taskId);
                await this.getTechnologyItemListRequest();
                this.showLoading = false;
            },
            getParamsData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                params.auditState = 1;
                const processItem = this.processList.find(x => x.id === params.processId) || {};
                params.processCode = processItem.code;
                params.processName = processItem.name;

                const modelItem = this.machineModelList.find(x => x.id === params.machineModelId) || {};
                params.machineModelCode = modelItem.code;
                params.machineModelName = modelItem.name;

                const spinTypeItem = this.spinTypeList.find(x => x.id === params.spinTypeId) || {};
                params.spinTypeCode = spinTypeItem.code;
                params.spinTypeName = spinTypeItem.name;
                return params;
            },
            onProcessChange() {
                this.$set(this.ruleForm, 'specSheetParamList', []);
                this.getTechnologyItemListRequest();
            },
            onSelectBatchCodeChange(e) {
                if (Object.keys(e).length) {
                    this.$set(this.ruleForm, 'batchCode', e.batchCode);
                }
            },
            onSelectEmpChange(e) {
                if (Object.keys(e).length) {
                    this.$set(this.ruleForm, 'specEmpId', e.id);
                    this.$set(this.ruleForm, 'specEmpCode', e.code);
                    this.$set(this.ruleForm, 'specEmpName', e.name);
                }
            },
            onSelectProductChange(e) {
                if (Object.keys(e).length) {
                    this.setProductDependentData(e);
                }
            },
            setProductDependentData(e) {
                this.$set(this.ruleForm, 'batchCodeId', null);
                this.$set(this.ruleForm, 'batchCode', '');
                this.$set(this.ruleForm, 'productId', e.id);
                this.$set(this.ruleForm, 'productCode', e.code);
                this.$set(this.ruleForm, 'productName', e.name);
                this.$set(this.ruleForm, 'productModels', e.models);
            },
            onConfirmBtn(type) {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.saveRequest(type);
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            saveRequest() {
                this.confirmBtnLoading = true;
                this.ruleForm.id = null;
                this.apiItem.save(this.getParamsData()).then(res => {
                    this.confirmBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-confirm', res.data.res);
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getMachineModelListRequest() {
                return spinMachineModelPage({ auditState: 1 }).then(res => {
                    if (res.data.status === 200) {
                        this.machineModelList = res.data.res;
                    }
                });
            },
            getTechnologyItemListRequest() {
                if (!this.ruleForm.processId) return;
                return spinTechnologyModelPage({
                    auditState: 1,
                    processId: this.ruleForm.processId,
                    spinTypeId: this.ruleForm.spinTypeId,
                    machineModelId: this.ruleForm.machineModelId
                }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || [];
                        if (resData.length && resData[0].itemList) {
                            const arr = resData[0].itemList.map(x => {
                                return {
                                    technologyModelItemId: x.id,
                                    dataType: x.dataType,
                                    ifBusi: x.ifBusi,
                                    ifNull: x.ifNull,
                                    ifWarning: x.ifWarning,
                                    specParamId: x.itemId,
                                    specParamCode: x.itemCode,
                                    specParamName: x.itemName,
                                    paramType: x.paramType,
                                    val: null,
                                    valMax: null,
                                    valMin: null
                                };
                            });
                            this.$set(this.ruleForm, 'specSheetParamList', arr);
                        }
                    }
                });
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
